package com.ebeijia.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ebeijia.context.RequestResponseContext;
import com.ebeijia.context.UserContext;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 * @author Yangpengju on 2015/09/19.
 * 
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	private static final String[] IGNORE_URI = {"login", "doLogin","image"};

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		boolean flag = false;
		String url = String.valueOf(request.getRequestURL());
		String uri = String.valueOf(request.getRequestURI());
		for (String s : IGNORE_URI) {
			if (url.contains(s)) {
				flag = true;
				break;
			}
		}
		if (!flag) {
			UserContext userContext = RequestResponseContext.getUserContext();
			if (userContext.getAccount() != null) {
				return true;
			}else{
				String backUrl = StringEscapeUtils.escapeHtml4(uri);
				response.sendRedirect(request.getContextPath()+"/doLogin.htm?backUrl=" +backUrl);
			}
		}
		return flag;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

}
